//
//  SEPrescriptionListViewController.swift
//  SmartEyeForDoctor
//
//  Created by QDSG on 2021/5/10.
//

import UIKit

class SEPrescriptionListViewController: SEBaseViewController {
    
    private var viewModel = SEPrescriptionViewModel()
    
    convenience init(inquiryId: String) {
        self.init()
        self.viewModel.inquiryId = inquiryId
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        bindViewModel()
    }
    
    override func setupUI() {
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(UIScreen.navigationBarMaxY)
        }
        
        tableView.tableFooterView = tableFooterView
        tableFooterView.frame = CGRect(x: 0, y: 0, width: view.width, height: 80)
    }
    
    private func bindViewModel() {
        viewModel.updateData = { [weak self] status in
            switch status {
            case .success:
                self?.endRefreshing()
                self?.tableView.reloadData {
                    self?.tableFooterView.isHidden = false
                }
            case .auth:
                self?.presentLoginViewController(selector: #selector(self?.loadData))
            case .failure: break
            }
        }
        
        viewModel.changeStatusHandler = { [weak self] status in
            switch status {
            case .success:
                SEHUD.show(message: "撤销处方成功")
                self?.loadData()
            case .auth:
                self?.presentLoginViewController(selector: nil)
            case .failure(let message):
                SEHUD.showError(message: message)
            }
        }
    }

    // MARK: - getter
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.backgroundColor = .background
        tableView.estimatedRowHeight = 60
        tableView.rowHeight = UITableView.automaticDimension
        tableView.separatorStyle = .none
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: UIScreen.bottomSafeHeight, right: 0)
        tableView.delegate = self
        tableView.dataSource = self
        
        tableView.se_header = SERefreshHeader { [weak self] in self?.loadData() }
        tableView.se_header?.beginRefreshing()
        
        tableView.register(SEPrescriptionListCell.nibForCell(),
                           forCellReuseIdentifier: SEPrescriptionListCell.reuseIdentifier())
        
        return tableView
    }()
    
    private lazy var tableFooterView: SEPrescriptionListNewView = {
        let tableFooterView = UINib.loadViewFrom(SEPrescriptionListNewView.self)
        tableFooterView.isHidden = true
        tableFooterView.newPrescriptionHandler = { [weak self] in self?.pushPrescriptionNewVc() }
        return tableFooterView
    }()
}

extension SEPrescriptionListViewController {
    @objc private func loadData() {
        viewModel.getListOfPrescription()
    }
    
    private func endRefreshing() {
        tableView.se_header?.endRefreshing()
    }
    
    // MARK: - push
    
    private func pushPrescriptionNewVc() {
        let prescription = SEPrescriptionMode.prescription(viewModel.inquiryId, "", true)
        let vc = SEPrescriptionNewViewController(mode: prescription)
        navigationController?.pushViewController(vc, animated: true)
        vc.updateHandler = { self.tableView.se_header?.beginRefreshing() }
    }
    
    @objc private func changePrescriptionStatus(_ viewModel: SEPrescriptionViewModel) {
        SEAlert.show(in: self, title: "撤销\(viewModel.prescriptionName)", message: "确定要撤销\(viewModel.prescriptionName)吗？", confirmTitle: "确定撤销") { _ in
            self.viewModel.changePrescriptionStatus(viewModel.prescription.id ?? "", status: .revoked)
        }
    }
}

// MARK: - UITableViewDataSource

extension SEPrescriptionListViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.numberOfRows
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: SEPrescriptionListCell.reuseIdentifier(),
                                                 for: indexPath) as! SEPrescriptionListCell
        let vm = viewModel.viewModel(at: indexPath)
        cell.update(with: vm)
        cell.changeHandler = { self.changePrescriptionStatus(vm) }
        return cell
    }
}

// MARK: - UITableViewDelegate

extension SEPrescriptionListViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let vm = viewModel.viewModel(at: indexPath)
        pushToPrescriptionDetail(vm)
    }
    
    private func pushToPrescriptionDetail(_ vm: SEPrescriptionViewModel) {
        let prescription = SEPrescriptionMode.prescription(vm.prescription.bisId ?? "", vm.prescription.id ?? "", false)
        let vc = SEPrescriptionNewViewController(mode: prescription)
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = UIView()
        header.backgroundColor = .clear
        return header
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
}
